package com.lmy.springCloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 1.配置SqlSessionFactory，使用seata代理数据源
 * 2.DataSourceProxy 是 io.seata.rm.datasource包下的
 */
@Configuration
@Slf4j
public class DataSourceProxyConfig {

    //指定mapper.xml文件位置
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    //配置druid数据源
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        log.info("druidDataSource.hashCode={}", druidDataSource.hashCode());
        return druidDataSource;
    }

    //配置数据源代理DataSourceProxy，使用seata代理数据源
    @Bean
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        log.info("dataSourceProxy() druidDataSource.hashCode={}", dataSource.hashCode());
        DataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
        log.info("dataSourceProxy.hashCode={}", dataSourceProxy.hashCode());
        return dataSourceProxy;
    }

    //配置SqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
        log.info("sqlSessionFactory() dataSourceProxy.hashCode={}", dataSourceProxy.hashCode());
        SqlSessionFactoryBean sqlSessionFactoryBean
                = new SqlSessionFactoryBean();
        //重新设置数据源，已被seata代理
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }
}
